package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 *
 * servlet
 * 控制文件下载
 *
 * 2018/5/13-10:26
 * 2018
 * Created by wuqiang on 2018/5/13.
 */
public class ServletDownload extends HttpServlet {
    /**
     * 控制文件的下载
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        /**
         * 首先读进来，
         * 然后再写出去
         */
        FileInputStream fis=null;
        try{
            String filePath = getServletContext().getRealPath("/images/test1.jpg");//获取文件的路径
            File file=new File(filePath);
            fis=new FileInputStream(file);
            ServletOutputStream os = resp.getOutputStream();
            byte[] buff=new byte[10];
            int len=0;
            while((len=fis.read(buff))!=-1){
                os.write(buff,0,len);
            }
        }catch (Exception e){
        }finally {
            if(fis!=null){
                fis.close();
            }
        }

    }
}
